#!/usr/bin/env python
# -*- encoding:utf-8 -*-
#**
#-------------------------------------------------------------------------------
#[Subject   -- SQL_Gen]
#[Author    -- tianxu.xxf]
#[Created   -- 2010.9.19]
#[Updated   -- ]
#[UpAuthor  -- ]
#-----------------------------------------------------------------------------*#
from Table import Table
from Util.Tools import toColumn,toCondition
from SQLException.TypeException import TypeException
from Const._JoinType import RIGHT_OUTER_JOIN

class View:
    """"""   

    def __init__(self,table,*columns):
        if not isinstance(table,Table) and not isinstance(table,View):
            raise TypeException
        self.__parents  = []
        self.__columns = []
        self.__condition = None
        self.__join_condition = None
        self.__order_by = []
        self.__sort_by = []
        
        self.__parents.append(table)
        self.__setColumn(columns)

    def SELECT(self,*columns):
        return View(self,*columns)

    def WHERE(self,condition):
        view = View(self)
        view._View__setCondition(condition)
        return view

    def JOIN(self,view,joinType=None):
        view = View(self)
        view._View__addParent(view)
        return view

    def RIGHT_OUTER_JOIN(self,view):
        self.JOIN(view,joinType=RIGHT_OUTER_JOIN)

    def ON(self,condition):
        view = View(self)
        view._View__setJoinCondition(condition)
        return view

    def ORDER_BY(self,*columns):
        view = View(self)
        view._View__setOrderBy(*columns)

    def SORT_BY(self,columns):
        view = View(self)
        view._View__setOrderBy(columns)

    def INSERT_INTO(self,name,*partitions):
        table = Table(name)
        table._Table__INSERT_FROM(self,*partitions)
        return table
        
    def __addParent(self,view):
        self.__parents.append(view)

    def __setColumn(self, columns):
        for column in columns:
            column = toColumn(column)
            self.__columns.append(column)
            self.__dict__[column.name] = column
    
    def __setCondition(self,condition):
        self.__condition = toCondition(condition)

    def __setJoinCondition(self,condition):
        self.__join_condition = toCondition(condition)
        
    def __setOrderBy(self,*columns):
        map(self.__order_by.append,map(toColumn, columns))

    def __setSortBy(self,*columns):
        map(self.__sort_by.append,map(toColumn, columns))

    def __getattr__(self,name):
        if not self.__dict__.has_key(name):
            self.__dict__[name]=toColumn(name)
    
